// pages/rooms/rooms.js
const { roomAPI } = require('../../utils/api.js')

Page({
  data: {
    roomList: [],
    currentRoomId: null,
    showRoomModal: false,
    currentRoom: null,
    loading: false
  },

  onLoad(options) {
    this.loadRoomList()
    
    // 如果有房间ID参数，选中该房间
    if (options.roomId) {
      this.setData({ currentRoomId: options.roomId })
    }
  },

  onShow() {
    this.loadRoomList()
  },

  onPullDownRefresh() {
    this.loadRoomList()
    wx.stopPullDownRefresh()
  },

  // 加载房间列表
  async loadRoomList() {
    this.setData({ loading: true })
    
    try {
      const rooms = await roomAPI.getRoomList()
      const roomsWithDevices = await this.enrichRoomData(rooms)
      
      this.setData({ 
        roomList: roomsWithDevices,
        loading: false
      })
    } catch (error) {
      console.error('加载房间列表失败:', error)
      this.setData({ loading: false })
      wx.showToast({ 
        title: '加载失败', 
        icon: 'error' 
      })
    }
  },

  // 丰富房间数据
  async enrichRoomData(rooms) {
    const app = getApp()
    const devices = app.globalData.deviceList
    
    return rooms.map(room => {
      const roomDevices = devices.filter(device => device.room === room.id)
      const onlineCount = roomDevices.filter(device => device.status === 'online').length
      
      return {
        ...room,
        devices: roomDevices.slice(0, 5), // 只显示前5个设备预览
        deviceCount: roomDevices.length,
        onlineCount: onlineCount,
        isFavorite: wx.getStorageSync(`room_favorite_${room.id}`) || false
      }
    })
  },

  // 房间点击事件 - 打开模态框
  onRoomTap(e) {
    const roomId = e.detail.roomId
    const room = this.data.roomList.find(r => r.id === roomId)
    
    if (room) {
      this.setData({
        currentRoom: room,
        showRoomModal: true
      })
    }
  },

  // 关闭模态框
  onCloseModal() {
    this.setData({
      showRoomModal: false,
      currentRoom: null
    })
  },

  // 模态框中设备点击
  onModalDeviceTap(e) {
    const deviceId = e.currentTarget.dataset.deviceId
    const roomId = this.data.currentRoom ? this.data.currentRoom.id : ''
    this.onDeviceTap({ detail: { deviceId, roomId } })
    this.onCloseModal()
  },

  // 模态框中设备开关切换
  onModalDeviceToggle(e) {
    const deviceId = e.currentTarget.dataset.deviceId
    const isOn = e.detail.value
    
    // 更新设备状态
    const app = getApp()
    app.updateDeviceStatus(deviceId, { powerState: isOn ? 'on' : 'off' })
    
    // 更新本地数据
    this.loadRoomList()
    
    wx.showToast({
      title: isOn ? '设备已开启' : '设备已关闭',
      icon: 'success'
    })
  },

  // 模态框中全部开关
  onModalToggleAll() {
    if (this.data.currentRoom) {
      const roomId = this.data.currentRoom.id
      const room = this.data.roomList.find(r => r.id === roomId)
      
      if (room && room.devices) {
        const allOn = room.devices.every(device => 
          device.status !== 'offline' && device.powerState === 'on'
        )
        const newState = !allOn
        
        room.devices.forEach(device => {
          if (device.status !== 'offline') {
            const app = getApp()
            app.updateDeviceStatus(device.id, {
              ...device.status,
              powerState: newState ? 'on' : 'off'
            })
          }
        })
        
        wx.showToast({
          title: newState ? '所有设备已开启' : '所有设备已关闭',
          icon: 'success'
        })
        
        this.loadRoomList()
      }
    }
    this.onCloseModal()
  },

  // 模态框中房间设置
  onModalRoomSettings() {
    if (this.data.currentRoom) {
      const roomId = this.data.currentRoom.id
      this.onRoomSettings({ detail: { roomId } })
    }
    this.onCloseModal()
  },

  // 模态框中添加设备
  onModalAddDevice() {
    if (this.data.currentRoom) {
      const roomId = this.data.currentRoom.id
      this.onAddDevice({ detail: { roomId } })
    }
    this.onCloseModal()
  },

  // 模态框中场景模式
  onModalRoomScene() {
    if (this.data.currentRoom) {
      const roomId = this.data.currentRoom.id
      this.onRoomScene({ detail: { roomId } })
    }
    this.onCloseModal()
  },

  // 设备点击事件
  onDeviceTap(e) {
    const { deviceId, roomId } = e.detail
    wx.navigateTo({
      url: `/pages/devices/devices?deviceId=${deviceId}&roomId=${roomId}&from=rooms`
    })
  },

  // 房间收藏事件
  onRoomFavorite(e) {
    const { roomId, isFavorite } = e.detail
    wx.setStorageSync(`room_favorite_${roomId}`, isFavorite)
    
    // 更新本地数据
    const roomList = this.data.roomList.map(room => 
      room.id === roomId ? { ...room, isFavorite } : room
    )
    this.setData({ roomList })
    
    wx.showToast({
      title: isFavorite ? '已收藏' : '已取消收藏',
      icon: 'success'
    })
  },

  // 添加设备事件
  onAddDevice(e) {
    const roomId = e.detail.roomId
    wx.navigateTo({
      url: `/pages/add-device/add-device?roomId=${roomId}`
    })
  },

  // 切换所有设备状态
  onToggleAllDevices(e) {
    const { roomId, state } = e.detail
    const app = getApp()
    const room = this.data.roomList.find(r => r.id === roomId)
    
    if (room && room.devices) {
      room.devices.forEach(device => {
        if (device.status !== 'offline') {
          app.updateDeviceStatus(device.id, {
            ...device.status,
            powerState: state ? 'on' : 'off'
          })
        }
      })
      
      wx.showToast({
        title: state ? '所有设备已开启' : '所有设备已关闭',
        icon: 'success'
      })
      
      // 刷新数据
      this.loadRoomList()
    }
  },

  // 房间设置事件
  onRoomSettings(e) {
    const roomId = e.detail.roomId
    wx.navigateTo({
      url: `/pages/room-settings/room-settings?roomId=${roomId}`
    })
  },

  // 房间场景事件
  onRoomScene(e) {
    const roomId = e.detail.roomId
    wx.navigateTo({
      url: `/pages/scenes/scenes?roomId=${roomId}`
    })
  },

  // 添加房间事件
  onAddRoom() {
    wx.navigateTo({
      url: '/pages/add-room/add-room'
    })
  }
})